package com.tc.itfarm.service.impl;

import com.google.common.collect.Lists;
import com.tc.itfarm.api.model.Page;
import com.tc.itfarm.api.model.PageList;
import com.tc.itfarm.api.model.SingleTableDao;
import com.tc.itfarm.api.util.PageQueryHelper;
import com.tc.itfarm.dao.CommentDao;
import com.tc.itfarm.model.Comment;
import com.tc.itfarm.model.CommentCriteria;
import com.tc.itfarm.model.ext.CommentVO;
import com.tc.itfarm.service.CommentService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * Created by wangdongdong on 2016/9/20.
 */
@Service
public class CommentServiceImpl extends BaseServiceImpl<Comment> implements CommentService {

    @Resource
    private CommentDao commentDao;

    @Override
    protected SingleTableDao getSingleDao() {
        return commentDao;
    }

    @Override
    public List<CommentVO> selectByArticle(Integer articleId) {
        List<CommentVO> list = Lists.newArrayList();
        CommentCriteria criteria = new CommentCriteria();
        criteria.setOrderByClause(" create_time desc");
        criteria.or().andTypeEqualTo((short) 0).andParentIdEqualTo(articleId);
        List<Comment> comments = commentDao.selectByCriteria(criteria);
        for (Comment c : comments) {
            CommentVO vo = new CommentVO();
            vo.setComment(c);
            setChild(vo);
            list.add(vo);
        }
        return list;
    }

    @Override
    public Integer countByArticle(Integer articleId) {
        CommentCriteria criteria = new CommentCriteria();
        criteria.or().andTypeEqualTo((short) 0).andParentIdEqualTo(articleId);
        return commentDao.countByCriteria(criteria);
    }

    @Override
    public List<Comment> selectRecent10() {
        CommentCriteria criteria = new CommentCriteria();
        criteria.or().andTypeEqualTo((short) 0);
        PageList<Comment> pageList = PageQueryHelper.queryPage(new Page(0, 10), criteria, commentDao, " create_time desc");
        return pageList.getData();
    }

    private void setChild(CommentVO vo){
        List<CommentVO> list = Lists.newArrayList();
        CommentCriteria criteria1 = new CommentCriteria();
        criteria1.setOrderByClause(" create_time desc");
        criteria1.or().andTypeEqualTo((short) 1).andParentIdEqualTo(vo.getComment().getRecordId());
        List<Comment> comments = commentDao.selectByCriteria(criteria1);
        for (Comment c : comments) {
            CommentVO v = new CommentVO();
            v.setComment(c);
            setChild(v);
            list.add(v);
        }
        vo.setChild(list);
    }
}
